package com.ita.os.client.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.ita.os.client.dao.ClientUserDao;
import com.ita.os.client.po.ClientUser;
import com.ita.os.client.util.DbUtil;

public class ClientUserDaoImpl implements ClientUserDao {

	@Override
	public ClientUser findUser(String tel, String pwd) {
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		ClientUser u = null;
		try {
			con = DbUtil.connect();
			String sql = "select * from clientuser where tel=? and pwd=?";
			pst = con.prepareStatement(sql);
			pst.setString(1,tel);
			pst.setString(2,pwd);
			rs= pst.executeQuery();
			while (rs.next()) {
				u = new ClientUser();
				u.setUsid(rs.getInt("usid"));
				u.setUname(rs.getString("uname"));
				u.setTel(rs.getString("tel"));
				u.setPwd(rs.getString("pwd"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
		DbUtil.free(con, pst, rs);
		}
		return u;
	}

	@Override
	public int addUser(ClientUser user) {
		Connection con = null;
		PreparedStatement pst = null;
		int count = 0;
		try {
			con = DbUtil.connect();
			con.setAutoCommit(false);
			String sql = "insert into clientuser values(my_seq.nextval,?,?,?)";
			pst = con.prepareStatement(sql);
			pst.setString(1, user.getUname());
			pst.setString(2, user.getTel());
			pst.setString(3, user.getPwd());
			count = pst.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}
		return count;
	}

}
